package com.leetcode.partition2;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/8/7 8:58
 */
public class LC121买卖股票的最佳时机 {

    public static int maxProfit(int[] prices) {
        return dynamicProgramming(prices);
    }

    public static void main(String[] args) {
        int[] prices = { 7, 1, 5, 3, 6, 4 };
//        int[] prices = { 7, 6, 4, 3, 1 };
//        int[] prices = { 1, 2, 3, 5 };
        System.out.println(maxProfit(prices));
    }

    /**
     * dp[i][0]代表第i天不持有股票的最大现金
     *      i-1天就已经不持有股票了dp[i-1][0]；i天卖出了股票dp[i-1][1]+prices[i]
     *      dp[i][0]=Math.max(dp[i-1][0], dp[i-1][1]+prices[i])
     * dp[i][1]代表第i天持有股票的最大现金
     *      i-1天就已经持有dp[i-1][1]；i天买入了股票-prices[i]
     *      dp[i][1]=Math.max(dp[i-1][1], -prices[i])
     */
    private static int dynamicProgramming(int[] prices) {
        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;       //第一天不买入
        dp[0][1] = -prices[0];      //第一天买入股票
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
        }
        return Math.max(dp[prices.length - 1][0], dp[prices.length - 1][1]);
    }

    //贪心算法
    private static int greedy(int[] prices) {
        int low = Integer.MAX_VALUE, answer = 0;
        for (int i = 0; i < prices.length; i++) {
            low = Math.min(low, prices[i]);     //取最小的买入价格
            answer = Math.max(answer, prices[i] - low);
        }
        return answer;
    }
}
